import classnames from 'classnames'
import { useNavigate } from 'react-router-dom'
import { NavBar, SearchBar } from 'antd-mobile'
import { observer } from 'mobx-react-lite'
import Icon from '@/components/Icon'
import styles from './index.module.scss'
import { useStore } from '@/store'
import { useState } from 'react'

const SearchPage = () => {
  const navigate = useNavigate()
  const { searchStore } = useStore()
  const [keyword, setKeyword] = useState('')
  const onChange = async (value: string) => {
    // 兼容后端查询字符串不能为空的bug
    if (!value) return
    setKeyword(value)
    // 调用搜索接口
    await searchStore.getSuggestData(value)
  }
  // 关键词高亮
  const highWord = (value: string) => {
    // a   abca  ->  <span>a</span>bc<span>a</span>   字符串全部替换
    return value.replaceAll(keyword, `<span>${keyword}</span>`)
  }
  // 清除搜索
  const onClear = () => {
    // 把当前的搜索结果列表清除 恢复原状
    searchStore.resetData()
  }
  return (
    <div className={styles.root}>
      <NavBar className="navbar" onBack={() => navigate(-1)}>
        <SearchBar
          placeholder="请输入关键字搜索"
          onChange={onChange}
          onClear={onClear}
        />
      </NavBar>

      <div className={classnames('search-result', true ? 'show' : '')}>
        {searchStore.suggestData.options.map((keyword) => {
          return (
            <div
              className="result-item"
              key={keyword}
              onClick={() => navigate(`/searchResult?q=${keyword}`)}>
              <Icon type="iconbtn_search" />
              {/* keyword -> <span>a</span>bc */}
              <div
                className="result-value text-overflow"
                dangerouslySetInnerHTML={{ __html: highWord(keyword) }}></div>
            </div>
          )
        })}
      </div>
    </div>
  )
}

export default observer(SearchPage)
